"use strict";
window.top === window.self;
var _console = window.console;
window.console = _console || {};
window.console.info = _console.info || function() {};
window.console.debug = _console.debug || function() {};
window.console.log = _console.log || function() {};



$(function() {

});
var JSTOOL = function() {
  /*
   * 美化所有checkbox与radio
   * 
   * $('input').iCheck('check'); — 将输入框的状态设置为checked
   * $('input').iCheck('uncheck'); — 移除 checked 状态
   * $('input').iCheck('toggle'); — toggle checked state
   * $('input').iCheck('disable'); — 将输入框的状态设置为 disabled
   * $('input').iCheck('enable'); — 移除 disabled 状态
   * $('input').iCheck('update'); — apply input changes, which were done
   * outside the plugin $('input').iCheck('destroy'); — 移除iCheck样式
   */
  this.changeCheck = function($dom) {
    $dom.iCheck({
      checkboxClass: 'icheckbox_flat-blue',
      radioClass: 'iradio_flat-blue'
    });
  };
  /*
   * 可以参考http://www.cnblogs.com/wuhuacong/p/4761637.html 美化select
   */
  this.changeSelect = function($dom, hasSearch) {
    var selectNum = 0;
    if (typeof(hasSearch) != 'undefined') {
      if (hasSearch == false) {
        selectNum = -1;
      }
    }
    $dom.select2({
      tags: true,
      maximumSelectionLength: 3,
      minimumResultsForSearch: selectNum
        // 最多能够选择的个数
    });
  };
  /*
   * 分页插件
   * mashaobo  2017年10月24日11:33:27 追加两个参数
   * pageSize:每页显示数量
   * rowCount:总数量
   * isNotShowDetail:是否不显示详细信息 true:不显示  false:默认显示
   */
  this.initPageDiv = function($dom, now, all, each, $dom2, change, pageSize, rowCount, isNotShowDetail) {
    if (parseInt(now) > parseInt(all)) {
      return;
    }
    //mashaobo  2017年10月30日10:26:53修改原来样式
    // var options = {
    //   currentPage: now, // 当前页
    //   totalPages: all, // 共几页
    //   numberOfPages: each, // 每次显示几页
    //   itemTexts: function(type, page, current) { // 修改显示文字
    //     switch (type) {
    //       case "first":
    //         return "第一页";
    //       case "prev":
    //         return "上一页";
    //       case "next":
    //         return "下一页";
    //       case "last":
    //         return "最后一页";
    //       case "page":
    //         return page;
    //     }
    //   },
    //   onPageClicked: function(event, originalEvent, type, page) { // 异步换页
    //     $dom2.val(page);
    //     change();
    //   }
    // }
    // $dom.bootstrapPaginator(options);

    //mashaobo 2017年10月30日10:27:29 修改为另外一个控件
    each = each >= 10 ? 5 : each - 0;
    each = each <= 3 ? 3 : each - 0;
    var options = {
      currentPage: now - 0, // 当前页
      pages: all - 0, // 共几页
      displayedPages: each, // 每次显示几页
      edges: 1,
      onPageClick: function(page, event) {
        $dom2.val(page);
        change();
      }
    }
    $dom.pagination(options);

    //区分有没有nav的情况
    var $parentDiv;
    if ($dom.parent().get(0).tagName.toUpperCase() == 'NAV') {
      $parentDiv = $dom.parent().parent();
    } else {
      $parentDiv = $dom.parent();
    }
    //判断有没有
    if ($parentDiv.hasClass('pull-right')) {
      $parentDiv.removeClass('pull-right').addClass('text-right');
    }

    if (!pageSize) {
      pageSize = 10;
    }
    if (!rowCount) {
      rowCount = 0;
    }
    //判断何时添加
    var htmlStr = '<p class="pull-left append-detail">每页显示<b>' + pageSize + '</b>条数据,共<b>' + rowCount + '</b>条数据</p>';
    if (!isNotShowDetail) {
      if ($parentDiv.find('.append-detail').length == 0) {
        $parentDiv.prepend(htmlStr);
      } else {
        $parentDiv.find('.append-detail').html('每页显示<b>' + pageSize + '</b>条数据,共<b>' + rowCount + '</b>条数据');
      }
    } else {
      $parentDiv.find('.append-detail').remove()
    }
  };
  /*
   * switch 选项插件
   * 
   */
  this.changeToSwitch = function($dom, left, right, onText, offText) {
    $dom.bootstrapSwitch({
      onText: onText,
      offText: offText,
      onColor: "success",
      offColor: "info",
      size: "small",
      onSwitchChange: function(event, state) {
        if (state == true) {
          left();
        } else {
          right();
        }
      }
    });
  };
  /* 日期框 */
  this.datePicker = function($dom, dataformat) {
    var _format = dataformat || "yyyymmdd"
    $dom.datetimepicker({
      format: _format, // "dd MM yyyy - HH:ii P",
      showMeridian: true,
      autoclose: true,
      todayBtn: true,
      minView: 2,
      language: 'zh-CN'
    });
  };
  /* 弹窗 */
  this.alert = function(title, content, callback, className) {
    var confirm = callback && typeof callback === "function" ? callback :
      function() {};
    if (myBrowser() == "IE8") {
      window.top.bootbox.alert({
        buttons: {
          ok: {
            label: '',
            className: 'btn-primary'
          }
        },
        message: content,
        callback: function() {
          confirm();
        },
        title: title
      });
    } else {
      var alertClass = "";
      if (typeof className == "undefined") {
        alertClass = 'offset4 col-md-4 col-md-offset-4';
      } else {
        alertClass = className;
      }
      window.top.$.alert({
        title: title,
        content: content,
        confirm: confirm,
        confirmButton: '确定',
        backgroundDismiss: false,
        confirmButtonClass: 'btn-primary',
        animation: 'zoom',
        closeAnimation: 'scale',
        columnClass: alertClass
      });
    }
  };
  this.confirm = function(title, content, okCallback, cancelCallback, initCallback) {
    var confirm = okCallback && typeof okCallback === "function" ? okCallback : function() {};
    var cancel = cancelCallback && typeof cancelCallback === "function" ? cancelCallback : function() {};
    var afterInit = initCallback && typeof initCallback == "function" ? initCallback : function() {};
    if (myBrowser() == "IE8") {
      var dialog = window.top.bootbox.confirm({
        buttons: {
          confirm: {
            label: '确认',
            className: 'btn-primary'
          },
          cancel: {
            label: '取消',
            className: 'btn-danger'
          }
        },
        message: content,
        callback: function(result) {
          if (result) {
            confirm(dialog.find(".bootbox-body"));
          } else {
            cancel();
          }
        },
        title: title
      });
      dialog.init(function() {
        afterInit(dialog.find(".bootbox-body"));
      });
    } else {
      var confirm = okCallback && typeof okCallback === "function" ? okCallback :
        function() {};
      var cancel = cancelCallback && typeof cancelCallback === "function" ? cancelCallback :
        function() {};
      window.top.$.confirm({
        title: title,
        content: content,
        confirm: confirm,
        cancel: cancel,
        confirmButton: '确定',
        cancelButton: '取消',
        confirmButtonClass: 'btn-primary',
        cancelButtonClass: 'btn-danger',
        backgroundDismiss: false,
        animation: 'zoom',
        closeAnimation: 'scale',
        onOpen: function() { afterInit(this.$content); }
      });
    }
  };
  this.dialog = function(title, content) {
    window.top.$.dialog({
      title: title,
      content: content,
      animation: 'zoom',
      closeAnimation: 'scale'
    });
  };
  // 处理空防止报错
  this.null2empty = function(str) {
    if (str == null) {
      return "";
    }
    return str;
  };
  // 刷新当前页面
  this.replacelocalhost = function(url) {
    var base = document.getElementsByTagName("base")[0];
    if (base) {
      window.location.replace(base.getAttribute("href") + url);
    } else {
      window.location.replace(url);
    }
  };
  // 获取跳页时父页面传来的参数
  this.getParam = function(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) {
      return unescape(r[2]);
    } else {
      return null;
    }
  }

  //获取当前调用协议
  this.getProtocol = function() {
    var p = window.location.protocol + "//";
    return p;
  }

  // 获取域名
  this.getUrlArea = function() {
    var r = window.location.host;
    return r;
  }

  // 防参数乱码 index为参数在url参数列表的顺序号
  this.getDecodeUrl = function(index) {
    var url = decodeURI(location.href);
    var result = url.split("?")[1].split("&")[index].split("=")[1];
    return result;
  }

  //手机号或座机
  this.isTelOrMobile = function(phone) {
      var phoneReg = /^((0\d{2,3}-\d{7,8})|(1[3584]\d{9})|(\d{8})|(0\d{2,3}\d{7,8}))$/;
      return phoneReg.test(phone);
    }
    //手机号或座机
  this.isMobile = function(phone) {
    var phoneReg = /^(((13[0-9]{1})|(14[0-9]{1})|(15[0-9]{1})|(18[0-9]{1})|(17[0-9]{1}))+\d{8})$/;
    return new RegExp(phoneReg).test(phone) && phone.length == 11;
  }

  // 处理缓存中json字符串的方法
  this.changeJsonToObj = function(json) {
    var goods = json.split("#");
    var obj = new Array();
    if (json != "") {
      for (var i = 0; i < goods.length; i++) {
        obj.push(JSON.parse(goods[i]));
      }
    }
    return obj;
  }

  //添加购物车
  this.addCart = function(goodId, goodinfo) {
      /*
       *购物车缓存相关变量
       *numOfCartGoodsInStorage 商品数
       *cartGoodsJsonInStorage  json串（#分隔）
       *goodId  （id具体值）用于判断商品是否存在
       */
      //先判断缓存购物车中是否已有此产品
      var goodIdInStorage = localStorage.getItem(goodId); //缓存中的产品id
      if (goodIdInStorage != null && goodIdInStorage != "null" && goodIdInStorage != "") {
        //			$("#info").text("该产品已被加入购物车，请勿重复添加");
        //	    	$("#dialog1").fadeIn(200);
        showAlert("该产品已被加入购物车，请勿重复添加");
      } else {
        //************************************************************************************//
    	console.info("==============addCart==========")
    	console.info(goodinfo)
		goodinfo = {
			"ID" : goodinfo.ID,
    		"NAME" : goodinfo.NAME,
    		"PRICE" : goodinfo.PRICE,
    		"COVER_IMAGE" : goodinfo.COVER_IMAGE,
    		"ALONE" : goodinfo.ALONE,
    		"NUM" : goodinfo.NUM
		};
        console.info(JSON.stringify(goodinfo))

        var cartGoodsJsonInStorage = localStorage.getItem("cartGoodsJsonInStorage"); //缓存中的购物车产品json串
        if (cartGoodsJsonInStorage != null && cartGoodsJsonInStorage != "null" && cartGoodsJsonInStorage != "") {
          cartGoodsJsonInStorage += "#" + JSON.stringify(goodinfo);
          localStorage.setItem("cartGoodsJsonInStorage", cartGoodsJsonInStorage);
        } else {
          localStorage.setItem("cartGoodsJsonInStorage", JSON.stringify(goodinfo));
        }
        $("#loadingToast").show();
        $.ajax({
          url: window.location.protocol + "//" + window.location.host + "/csfwpt_console/restful/shopping/chart",
          data: {
            goodsInfo: localStorage.getItem("cartGoodsJsonInStorage")
          },
          dataType: "TEXT",
          type: "POST"
        }).done(function(data) {
          if(data!=null && data!="" && data!="null" && data!=[] && data!="[]"){
	    	  console.info(data);
	          var $toastsuccessGoodDetail = $("#toastsuccessGoodDetail");
	          if (data == "SUCCESS") {
	            $("#loadingToast").hide();
	            localStorage.setItem(goodId, goodId);
	            //商品信息保存在浏览器缓存中  购物车从库中取数据时要将localStorage清空重新保存
	
	            //改变缓存中的购物车产品数量
	            var n = localStorage.getItem("numOfCartGoodsInStorage");
	            localStorage.setItem("numOfCartGoodsInStorage", (parseInt(n) + 1));
	            if ($toastsuccessGoodDetail.css("display") != "none") return;
	            setTimeout(function() {
	              $toastsuccessGoodDetail.fadeIn(300);
	            }, 100);
	            setTimeout(function() {
	              $toastsuccessGoodDetail.fadeOut(300);
	              $("#numOfCart").show();
	              $("#numOfCartHome").show();
	              $("#cartNum").text(localStorage.getItem("numOfCartGoodsInStorage"));
	              $("#cartNumHome").text(localStorage.getItem("numOfCartGoodsInStorage"));
	              $(window.parent.document).find("#numOfCartHome").show();
	              $(window.parent.document).find("#cartNumHome").show();
	              $(window.parent.document).find("#normalCartHome").hide();
	              $(window.parent.document).find("#cartNumHome").text(localStorage.getItem("numOfCartGoodsInStorage"));
	              $("#normalCart").hide();
	            }, 1000);
	          } else if (data == "FAIL") {
	            $("#loadingToast").hide();
	            //					$("#info").text("添加失败，请联系管理员");
	            //			    	$("#dialog1").fadeIn(200);
	            showAlert("添加失败，请联系管理员");
	          } else if (data == "NOCOMPANY") {
	            $("#loadingToast").hide();
	            //					$("#info2").text("您还未选定企业");
	            //			    	$("#dialog2").fadeIn(200);
	            showAlertWithPic("您还没有选定企业", function() {
	              sessionStorage.setItem("toCart", 1);
	              var url = "sale_index.html?toCompany=1";
	              window.parent.location.href = url;
	            }, "去选定", "../../static/common/images/weixin/noselect.png");
	          }
          }
        });
      }
    }
    //删除购物车
  this.deleteGoodsFromCart = function(ids, ifToBalance) {
    var r = "";
    var goodsInStorage = tool.changeJsonToObj(localStorage
      .getItem("cartGoodsJsonInStorage"));
    var temp = []; // 临时数组1
    var goodsInStorageResult = []; // 临时数组2
    var idss = ids.split(",")
    console.info(idss)
    if (idss.length != 0) {
      for (var i = 0; i < idss.length; i++) {
        temp[idss[i]] = true;
        // 删除 用于判断商品是否在购物车中的变量
        localStorage.removeItem(idss[i]);
        // 改变购物车标签商品数量角标
        var n = localStorage.getItem("numOfCartGoodsInStorage");
        localStorage.setItem("numOfCartGoodsInStorage", n - 1);
      }
      // 删除缓存中json字符串中被选中的商品信息
      if (goodsInStorage.length != 0) {
        for (var j = 0; j < goodsInStorage.length; j++) {
          if (!temp[goodsInStorage[j].ID]) {
            goodsInStorageResult.push(goodsInStorage[j]);
          }
        }
      }
      console.info(goodsInStorageResult)
        // 将删除后的对象转为json存入缓存及数据库
      var cartGoodsJsonInStorage = "";
      if (goodsInStorageResult.length != 0) {
        cartGoodsJsonInStorage = JSON
          .stringify(goodsInStorageResult[0]);
        for (var n = 1; n < goodsInStorageResult.length; n++) {
          cartGoodsJsonInStorage += "#" +
            JSON.stringify(goodsInStorageResult[n]);
        }
        console.info(cartGoodsJsonInStorage)
        localStorage.setItem("cartGoodsJsonInStorage",
          cartGoodsJsonInStorage);
      }
      $.ajax({
        url: window.location.protocol + "//" + window.location.host +
          "/csfwpt_console/restful/shopping/chart",
        data: {
          goodsInfo: cartGoodsJsonInStorage
        },
        dataType: "TEXT",
        type: "POST"
      }).done(function(data) {
        if(data!=null && data!="" && data!="null" && data!=[] && data!="[]"){
        	console.info(data);
            if (data == "NOCOMPANY") {
              $("#loadingToast").hide();
              //			$("#infoInCart").text("您还未选定企业");
              //	    	$("#dialogInCart").fadeIn(200);
              showAlertWithPic("您还没有选定企业", function() {
                sessionStorage.setItem("toCart", 1);
                var url = "sale_index.html?toCompany=1";
                window.parent.location.href = url;
              }, "去选定", "../../static/common/images/weixin/noselect.png");
            } else {
              if (ifToBalance == 0 || ifToBalance == "0") {
                if (data == "SUCCESS") {
                  createPage();
                } else if (data == "FAIL") {
                  $("#loadingToast").hide();
                  //        			$("#info").text("删除失败，请联系管理员");
                  //        			$("#dialog1").fadeIn(200);
                  showAlert("删除失败，请联系管理员");
                }
              } else {
                if (data == "SUCCESS") {
                  console.info("pay")
                    // 模拟支付成功
                  var testMode = localStorage.getItem("testMode");
                  if (testMode == "32" || testMode == 32) {
                    var url = "pay_success.html";
                    window.location.href = encodeURI(url);
                  }
                  //            var url = "pay_success.html";
                  //            window.location.href = encodeURI(url);
                } else if (data == "FAIL") {
                  console.info("fail");
                }
              }
            }
        }
      });
    }
    return r;
  }

  this.changePageUrl = function(title, url) {
    // 改变当前页url
    function pushHistory() {
      var state = {
        title: title,
        url: url
      };
      window.history.replaceState(state, title, url);
    }
    // 支付后续操作如果后退直接后退到输入税号页
    var bool = false;
    setTimeout(function() {
      bool = true;
    }, 100);
    pushHistory();
    window.addEventListener("popstate", function(e) {
      if (bool) {
        window.history.go(-1);
      } else {
        pushHistory();
      }
    }, false);
  }

  this.changeParentPageUrl = function(title, url) {
    // 改变当前页url
    function pushHistory() {
      var state = {
        title: title,
        url: url
      };
      window.parent.history.replaceState(state, title, url);
    }
    // 支付后续操作如果后退直接后退到输入税号页
    var bool = false;
    setTimeout(function() {
      bool = true;
    }, 100);
    pushHistory();
    window.addEventListener("popstate", function(e) {
      if (bool) {
        window.history.go(-1);
      } else {
        pushHistory();
      }
    }, false);
  }

  this.showModal = function() {
    // var html = '<div class="modal fade" id="modal1">'+
    // ' <div class="modal-dialog ">'+
    // '<div class="modal-content">'+
    // ' <div class="modal-header">'+
    // ' <button type="button" class="close" data-dismiss="modal"
    // aria-hidden="false">×</button>'+
    // '<h4 class="modal-title">模板详情</h4>'+
    // '</div>'+
    // '<div class="modal-body">'+
    // '<form>'+
    // ' <div class="form-group"> '+
    // ' <label class="control-label">模板名称：</label> '+
    // ' <span id="moTitle"></span>'+
    // ' </div> '+
    // ' <div class="form-group"> '+
    // ' <label class="control-label">模板CODE：</label> '+
    // ' <span id="moCode"></span>'+
    // ' </div> '+
    // ' <div class="form-group"> '+
    // ' <label class="control-label">模板内容：</label> '+
    // ' <span id="moContent"></span>'+
    // ' </div> '+
    // ' </form>'+
    // ' </div>'+
    // ' <div class="modal-footer">'+
    // ' <a class="btn btn-default" data-dismiss="modal">关闭</a>'+
    // ' </div>'+
    // '</div>'+
    // '</div>'+
    // '</div>';
    // alert(html)
    // $("#workspace").append(html);
    $("#modal1").modal("show");
  }



  // 打开模态框
  var fatherBody = $(window.top.document.body);
  this.openModal = function(validate, saveInfo, watermark, floor, callback) {
    fatherBody.find("#moda").remove();
    var id = 'moda';
    var dialog = $('#' + id);

    if (dialog.length == 0) {
      dialog = $('<div class="modal fade" role="dialog" id="' + id +
        '"/>');
      dialog.appendTo(fatherBody);
    }
    dialog.load("tool/toImageUpload?validate=" + validate + "&saveInfo=" +
      saveInfo + "&watermark=" + encodeURI(encodeURI(watermark)) +
      "&floor=" + floor + "&callback=" + callback,
      function() {
        dialog.modal({
          backdrop: false
        });
        //mashaobo 2017年10月19日13:23:04修改
        getDateList();
        window.top.$('#accordion').on('hidden.bs.collapse', function(e) {
          $(e.target).find('.img-body-block').html('<h4 class="text-center">暂无结果</h4>');
          $(e.target).find('#alreadyPageBlock').remove();
        });
        window.top.$('#accordion').on('show.bs.collapse', function(e) {
          window.top.$("#currentPage").val('1');
          var currentDate = $(e.target).attr('data-date');
          getImgListByDate(currentDate, 1);
        });
        window.top.$("#btnImgSearchByRemark").click(function(e) {
          imgSearchByRemark();
        });


        window.top.$("#txtImgSearchInput").keydown(function(e) {
          var ev = document.all ? window.event : e;
          if (ev.keyCode == 13) {
            window.top.$("#btnImgSearchByRemark").click();
            return false; //防止其他默认事件
          }
        });

      });
    $('#pdfDownload_button').attr('data-dismiss', '');
  }
  this.openFileModal = function(validate, saveInfo, watermark, floor, callback) {
    var id = 'moda';
    var dialog = $('#' + id);
    if (dialog.length == 0) {
      dialog = $('<div class="modal fade" role="dialog" id="' + id +
        '"/>');
      dialog.appendTo(fatherBody);
    }
    dialog.load("tool/toFileUpload?compress=" + validate + "&saveInfo=" +
      saveInfo + "&watermark=" + encodeURI(encodeURI(watermark)) +
      "&floor=" + floor + "&callback=" + callback,
      function() {
        dialog.modal({
          backdrop: false
        });
      });
    $('#pdfDownload_button').attr('data-dismiss', '');
    // fatherBody
    // .append("<div id='backdropId' class='modal-backdrop fade
    // in'></div>");
  }

  // 关闭模态框
  //	this.closeModal = function() {
  //		var fatherBody = $(window.top.document.body);
  //		console.info(fatherBody.find("#moda"))
  //		fatherBody.find("#moda").on('hidden.bs.modal', function(e) {
  //			//fatherBody.find("#backdropId").removeData("bs.modal");
  //			 $(this).removeData("bs.modal");
  //		});
  //	}

  this.getUploadResult = function(input, validate, saveInfo, floor, watermark) {
    if (this.value == "") {
      return;
    }
    //NOTE:666没啥实际意义,就是后来升级图片管理功能时,和原来的做个区分
    if (validate == '666' && saveInfo == '666') {
      uploadImage('666', '666', input, "tool/blank",
        function(data) {
          uploadResult = data;
          if (floor == "0") {
            window.parent[0].showImage(uploadResult);
          } else if (floor == "1") {
            window.parent.showImage(uploadResult);
          } else {
            window.parent[0].showImage(uploadResult);
          }
        });
    } else {
      uploadImage(validate, saveInfo, watermark, "tool/blank",
        function(data) {
          uploadResult = data;
          if (floor == "0") {
            window.parent[0].showImage(uploadResult);
          } else if (floor == "1") {
            window.parent.showImage(uploadResult);
          } else {
            window.parent[0].showImage(uploadResult);
          }
        });
    }


  }



  this.getFileUploadResult = function(compress) {
    // alert("file上传");
    if (this.value == "") {
      return;
    }
    var flag = true;
    //true为不压缩，false为压缩
    /*if(compress == 'adFile'){
    	flag = false;
    }*/
    uploadResource(flag, "tool/blank",
      function(data) {
        uploadResult = data;
        window.parent[0].showFile(uploadResult);
      });
  }


  this.ensure = function() {
    console.info(fatherBody.find("#moda"))
      //$("#closeModal").click();
      //	$("#moda").modal("hide");
    if (window.parent[0].showImage) {
      console.log(window.parent);
      window.parent[0].showImage(uploadResult);
    } else {
      console.log(window.parent);
    }
  }

  //计算报名费用
  //formual：公式      totalFee：课程价格（会员非会员分开计算）     num：报名人数
  this.showFee = function(formual, totalFee, num) {
    var M = parseFloat(totalFee);
    var N = parseFloat(num);
    var f = eval(formual);
    return f;
  }

  //从微信用户中心跳转来
  this.saveSessionFromUserCenter = function(webUserId) {
    $.ajax({
      url: window.location.protocol + "//" + window.location.host + "/csfwpt_console/restful/user/fromWxUserCenter",
      data: { webUserId: webUserId },
      async: false,
      type: "GET"
    }).done(function(data) {
      if (data != "" && data != null && data != "[]" && data != []) {
        localStorage.setItem("openId", data.replace(/\"/g, ""));
        console.info("openid已保存");
        console.info(localStorage.getItem("openId"));
      }
    });
  }

  //点击默认返回按钮关闭浏览器
  this.closeWindow = function() {
    var bool = false;
    setTimeout(function() {
      bool = true;
    }, 100);
    pushHistory();
    window.addEventListener("popstate", function(e) {
      if (bool) {
        //				alert("我监听到了浏览器的返回按钮事件啦");//根据自己的需求实现自己的功能 
        //				WeixinJSBridge.call('closeWindow');
        window.parent.location.href = window.location.protocol + "//" + window.location.host + "/wechatcs/";
      } else {
        pushHistory();
      }
    }, false);
  }

  /**
   * 替换某个字符串为另外一个字符串函数
   * 
   * @param {any} bigStr  全部字符
   * @param {any} str1 被替换的字符
   * @param {any} str2 新字符
   * @returns 新的字符串
   */
  this.replaceAll = function(bigStr, str1, str2) { //把bigStr中的所有str1替换为str2
    var reg = new RegExp(str1, 'gm');
    return bigStr.replace(reg, str2);
  }
  
  /**
   * 根据useragent判断设备的方法
   */
  this.getUserAgent = function(){
	  var ua = navigator.userAgent;
	  if(ua){
		  if(ua.indexOf("Windows NT")!=-1){
			  return "Windows";
		  }else if(ua.indexOf("Macintosh")!=-1){
			  return "iMac";
		  }else if(ua.indexOf("iPad")!=-1){
			  return "iPad";
		  }else if(ua.indexOf("iPhone")!=-1){
			  return "iPhone";
		  }else if(ua.indexOf("Android")!=-1){
			  return "Android";
		  }else{
			  return "other";
		  }
	  }
  }

};

var tool = new JSTOOL();
var uploadResult = null;

// 复制到剪切板
function paste() {
  if (window.clipboardData) {
    window.clipboardData.clearData();
    clipboardData.setData("Text", $.trim($("#sqFrame").val()));
    tool.alert("提示", "复制成功！");
  } else {
    tool.alert("提示", "复制失败！请手动复制");
  }
};
// 判断浏览器版本
function myBrowser() {
  var userAgent = navigator.userAgent; // 取得浏览器的userAgent字符串
  var isOpera = userAgent.indexOf("Opera") > -1; // 判断是否Opera浏览器
  var isIE = userAgent.indexOf("compatible") > -1 &&
    userAgent.indexOf("MSIE") > -1 && !isOpera; // 判断是否IE浏览器
  var isFF = userAgent.indexOf("Firefox") > -1; // 判断是否Firefox浏览器
  var isSafari = userAgent.indexOf("Safari") > -1; // 判断是否Safari浏览器
  if (isIE) {
    var IE5 = IE55 = IE6 = IE7 = IE8 = false;
    var reIE = new RegExp("MSIE (\\d+\\.\\d+);");
    reIE.test(userAgent);
    var fIEVersion = parseFloat(RegExp["$1"]);
    IE55 = fIEVersion == 5.5;
    IE6 = fIEVersion == 6.0;
    IE7 = fIEVersion == 7.0;
    IE8 = fIEVersion == 8.0;
    if (IE55) {
      return "IE55";
    }
    if (IE6) {
      return "IE6";
    }
    if (IE7) {
      return "IE7";
    }
    if (IE8) {
      return "IE8";
    }
  } // isIE end
  if (isFF) {
    return "FF";
  }
  if (isOpera) {
    return "Opera";
  }
};

// 查询钥匙盘信息
function getKeyno() {
  var keyInfo = null;
  if (!window.top['_CACHE']) {
    var fpTool = new InvoiceTools(window.top, {
      serverIp: "221.238.143.36", // 开票服务器地址
      serverPort: "8081", // 开票服务器服务端口
      keypwd: "88888888", // 开票服务器密钥
      kpzdbs: "TX-01", // 开票终端标识
      kpr: {
        xhdwsbh: "120117777303334", // 销货单位纳税人识别号
        xhdwmc: "天津神州浩天科技有限公司", // 销货单位名称
        xhdwdzdh: "天津市华苑产业区榕苑路15号1号楼B-2008022-58389701", // 销货单位地址名称
        xhdwyhzh: "天津市农业银行华苑软件大厦支行02200401040007690" // 销货单位银行账户
      }
    });
    keyInfo = fpTool.searchKeyInfo();
  } else {
    keyInfo = window.top['_CACHE'].searchKeyInfo();
  }
  if (!keyInfo.success) {
    console.info("查询钥匙盘信息失败，失败原因：" + keyInfo.message);
  } else {
    // 获取kpzdbs，开票终端表示
    var key = keyInfo.bean.keyno;
    // var key = "33123456789";
    if (key != null && key != "" && key != "null") {
      return key.substring(2, key.length);
    }
  }
}
/**
 * 通过的新开页面跳转方法
 */
function openNewPage(url) {
  window.open(url);
}

function pushHistory() {
  var state = {
    title: "title",
    url: window.location.protocol + "//" + window.location.host + "/wechatcs/"
  };
  window.history.pushState(state, "title", "");
}



function toTimestamp(timestr) {
  //   return new Date(timestr).setHours(0); //设置时间为一天开始
  return Date.parse(new Date(timestr)).toString() == "NaN" ? 0 : Date.parse(new Date(timestr));
}
/**
 * 时间戳转化为正常时间 
 * @param {any} shijianchuo  时间戳 精确到毫秒
 * @returns 正常时间
 */
function toNormalTime(shijianchuo) {
  var time = new Date(parseInt(shijianchuo));
  var y = time.getFullYear();
  var m = time.getMonth() + 1;
  var d = time.getDate();
  var h = time.getHours();
  var mm = time.getMinutes();
  var s = time.getSeconds();
  return y + '-' + add0(m) + '-' + add0(d) + ' ' + add0(h) + ':' + add0(mm) + ':' + add0(s);
}

function add0(m) {
  return m < 10 ? '0' + m : m;
}


/**
 * 分隔获取各个参数
 * 根据URL地址获取其参数
 */
function UrlSearch() {
  var name, value;
  var str = location.href; //取得整个地址栏
  var num = str.indexOf("?");
  str = str.substr(num + 1);
  var arr = str.split("&"); //各个参数放到数组里
  for (var i = 0; i < arr.length; i++) {
    num = arr[i].indexOf("=");
    if (num > 0) {
      name = arr[i].substring(0, num);
      value = arr[i].substr(num + 1);
      this[name] = value;
    }
  }
}



function getImgListByDate(imgdate, pageindex) {
  $.ajax({
    type: "POST",
    url: "knowledge/article/searchImage", //TODO 修改此时链接
    data: {
      date: imgdate,
      currentPage: pageindex
    },
    dataType: "json",
    success: function(data, textStatus, jqXHR) {
      if (data != null && data != "") {
        if (data.success) {
          if (data.bean.data.length > 0) {
            window.top.$("#date-" + imgdate).find("#alreadyPageBlock").remove();
            var htmlStr = "";
            for (var index = 0; index < data.bean.data.length; index++) {
              var element = data.bean.data[index];
              var singleImgDom =
                '<div class="col-md-2 img-single-block">' +
                '<img src="' + element.url + '" alt="' + element.remark + '" data-imgId="' + element.id + '" onclick="tool.getUploadResult(this,\'666\',\'666\',\'\',\'\')";>' +
                '<p class="p-imgremark" onclick="preimgclick(this)">' + element.remark + '</p>' +
                '</div>';
              htmlStr += singleImgDom;
            }
            window.top.$("#date-" + imgdate).find('.img-body-block').html(htmlStr);
            window.top.$("#date-" + imgdate).find('.img-body-block').after('<div class="text-right" id="alreadyPageBlock"><ul class="pagination" id="alreadyPage"></ul></div>');
            //生成分页控件
            tool.initPageDiv(window.top.$("#date-" + imgdate).find("#alreadyPage"), //在哪里生成页码
              data.bean.pageNum, //当前页
              data.bean.pageCount, //一共多少页
              3, //每次显示多少页
              window.top.$("#currentPage"), //将每次的分页的页码放到这个input里
              function() {
                getImgListByDate(imgdate, window.top.$("#currentPage").val());
              },
              data.bean.pageSize,
              data.bean.rowCount, true
            );
          } else {
            if (data.bean.rowCount > 0 && pageindex > 1) {
              getImgListByDate(imgdate, pageindex - 1)
            } else {
              window.top.$("#date-" + imgdate).find("#alreadyPageBlock").remove();
              window.top.$("#date-" + imgdate).find('.img-body-block').html('<h4 class="text-center">暂无结果</h4>');
            }
          }
        } else {
          window.top.$("#date-" + imgdate).find("#alreadyPageBlock").remove();
          window.top.$("#date-" + imgdate).find('.img-body-block').html('<h4 class="text-center">暂无结果</h4>');
        }

      } else {
        window.top.$("#date-" + imgdate).find("#alreadyPageBlock").remove();
        window.top.$("#date-" + imgdate).find('.img-body-block').html('<h4 class="text-center">暂无结果</h4>');

      }
    },
    error: function(response) {
      //NOTE 获取服务出错时提示
      // tool.alert("提示", "请求服务失败,请重试!");
    },
    complete: function(xhr, textStatus) {
      //NOTE 异步事件完成后需要操作的内容
    }
  });
}

/**
 * 时间戳转化为正常时间 
 * @param {any} shijianchuo  时间戳 精确到毫秒
 * @returns 正常时间
 */
function getToday() {
  var time = new Date();
  var y = time.getFullYear();
  var m = time.getMonth() + 1;
  var d = time.getDate();
  return y + '-' + add0(m) + '-' + add0(d);
}

function add0(m) { return m < 10 ? '0' + m : m; }